package presistencia.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import presistencia.conexao.Conexao;
import presistencia.interfaces.ContaDAO;
import beans.Conta;

public class ContaDAOImpl implements ContaDAO {

	private Conexao conexao;
	
	public ContaDAOImpl(Conexao conexao) {
		this.conexao = conexao;
	}
	
	@Override
	public long inserir(Conta objeto) throws SQLException {
		PreparedStatement preparedStatement = conexao.getPreparedStatement("INSERT INTO contas (nm_conta) VALUES (?)");
		preparedStatement.setString(1, objeto.getNome());
		preparedStatement.executeUpdate();
		long extractId = Util.extractId(preparedStatement.getGeneratedKeys());
		preparedStatement.close();
		return 	extractId;	

	}

	@Override
	public void deletar(Conta objeto) throws SQLException {
		PreparedStatement preparedStatement = conexao.getPreparedStatement("DELETE FROM CONTAS WHERE cd_conta = ?");
		preparedStatement.setLong(1, objeto.getCodigo());
		preparedStatement.executeUpdate();
		preparedStatement.close();
	}

	@Override
	public void atualizar(Conta objeto) throws SQLException {
		PreparedStatement preparedStatement = conexao.getPreparedStatement("UPDATE contas SET nm_conta=? WHERE cd_conta = ?");
		preparedStatement.setString(1, objeto.getNome());
		preparedStatement.setLong(2, objeto.getCodigo());
		preparedStatement.executeUpdate();
		preparedStatement.close();
	}

	@Override
	public Conta buscarID(long id) throws SQLException {
		Conta credito = null;
		PreparedStatement preparedStatement = conexao.getPreparedStatement("SELECT cd_conta, nm_conta FROM contas WHERE cd_conta = ?");
		preparedStatement.setLong(1, id);
		ResultSet query = preparedStatement.executeQuery();
		if(query.next()){
			credito= bindCredito(query);			
		}
		query.close();
		preparedStatement.close();
		return credito;		

	}
	
	@Override
	public List<Conta> buscarTodos() throws SQLException {
		
		PreparedStatement preparedStatement = conexao.getPreparedStatement("SELECT cd_conta, nm_conta FROM contas order by nm_conta");
		ResultSet query = preparedStatement.executeQuery();
		
		return bindCreditos(query);
	}
	
	private Conta bindCredito(ResultSet query) throws SQLException{
		return new Conta(query.getLong("cd_conta"), query.getString("nm_conta"));
	}
	
	private List<Conta> bindCreditos(ResultSet query) throws SQLException{
		List<Conta> creditos = new ArrayList<Conta>();
		
		while(query.next()){
			creditos.add(bindCredito(query));
		}
		
		return creditos;
	}

}
